import { useEffect, useRef, useState } from "react";
import { io } from "socket.io-client";

export const useCountDown = (num = 60) => {
  const [count, setCount] = useState(num);
  const [isDown, setIsDown] = useState(false);
  const timer = useRef(null);
  function start() {
    setIsDown(true);
    timer.current = setInterval(() => {
      setCount((prev) => prev - 1);
    }, 1000);
  }
  useEffect(() => {
    if (count <= 0) {
      setIsDown(false);
      clearInterval(timer.current);
      setCount(num);
    }
  }, [count]);
  useEffect(() => {
    return () => clearInterval(timer.current);
  }, []);

  return { start, count, isDown };
};

export const useFd = () => {
  const timer = useRef(null);
  function fd(cb) {
    return (...arg) => {
      clearInterval(timer.current);
      timer.current = setTimeout(() => {
        cb(...arg);
      }, 500);
    };
  }
  return fd;
};

export const useSocket = (url, cb) => {
  const socket = useRef(null);
  useEffect(() => {
    socket.current = io(url, {
      reconnection: true, // 如果连接不通畅，则会自动重连尝试
      reconnectionAttempts: 5, // 设置重连的次数
      reconnectionDelay: 5000, // 重连的延迟时间 ms
      timeout: 8000, // 超时时间 ms
    });
    socket.current.on('message',cb)
    return ()=>socket.current.close()
  }, []);
  return socket
};
